<?php
/*
 * Creative Bulletin Board Generation 3
 * Version 1.0 Beta 1
 +------------------------------------
 * Core View Class, Layouts + Templating
 * Started: August 22, 2009 11:02:52 AM
 * Script version: 1.0.1
 * Estimated changes to date 56 million
 +------------------------------------
 */
class view{
	public function __construct(){
		global $db;
		$layout = $db->conf_value("layout_".APP_TYPE);
		require_once(CORE_PATH."views/layout_".APP_TYPE.".php");
		require_once(PUBLIC_PATH."layout/".APP_TYPE."/{$layout}.php");
		$this->layout = new Layout;
		$this->layoutInfo = $this->layout->layoutInfo;
		if(isset($_SESSION["cf_username"], $_SESSION["cf_controller"])){
			require_once(BASE_PATH."applications/universal/user/controllers/user.php"); # Dare I say - Even worse workarounds?
			$this->userController = unserialize($_SESSION["cf_controller"]);
			$this->uid = $this->userController->getUID();
		}
		else{
			$this->uid = -1;
		}
		$this->content = "";
	}
	
	public function outVars($var){
		require(CORE_PATH."varSystem.php");
		return $var;
	}
	
	public function initHeader($title, $desc = ""){
		global $db, $timer;
		$timer['output_start'] = round(microtime(), 3);
		$this->layoutArray = array();
		$query = $db->select(APP_TYPE."_nav", "*", 0, " ORDER BY `order` ASC");
		if($query !== false){
			if($db->num_rows($query) > 0){
				while($array = $db->fetch_array($query)){
					$this->layoutArray[] = array(
						"title" => $array['title'],
						"uri" => "?app=".$array['application']."&module=".$array['module'],
						"icon" => $array['icon'],
						"application" => $array['application'],
						"module" => $array['module']
					);
				}
			}
			$this->layout->navigation($this->layoutArray);
		}
		else{
			$this->layout->navigation(array());
		}
		$this->layout->header($db->conf_value("system_name")." - ".$title, $desc);
	}
	
	public function footer(){
		// Are we in shutdown? Weee!
		global $db, $timer;
		$queries = $db->queries;
		$dbg = ($db->conf_value("advanced_debug") == "true" ? true : false);
		if($dbg == "true"){
			$queries_run = $db->queries_run;
		}
		else $queries_run = "";
		$bootstrapTime = round($timer['bootstrap_end'] - $timer['bootstrap_start'], 3);
		$timer['view_end'] = round(microtime(), 3); # Look at our timer!
		$outputTime = round($timer['output_start'] - $timer['bootstrap_start'], 3);
		$finalTime = round($timer['view_end'] - $timer['bootstrap_start'], 3);
		$this->layout->footer(array("queries" => $queries, "boot" => $bootstrapTime, "gentime" => $finalTime, "outputtime" => $outputTime, "queries_ran" => $queries_run), $dbg);
	}
	
	public function generateRedirMeta($uri, $seconds = 2){
		return "<meta http-equiv='refresh' content='{$seconds};url={$uri}' />";
	}
	
	public function fetchTemplate($templname, $standalone = 0, $interface = APP_TYPE, $application = APPLICATION){
		if($standalone !== 0){
			$file = PUBLIC_PATH."templates/".$templname.".tpl";
		}
		else $file = BASE_PATH."applications/".$interface."/".$application."/tpl/".$templname.".tpl";
		if(!file_exists($file)){
			if(!IN_WINDOWS and strtolower($templname) != $templname) return fetchTemplate(strtolower($templname), $standalone, $interface, $application);
			else trigger_error("Template {$file} not found");
		}
		else{
			$file_data = file_get_contents($file);
			return $file_data;
		}
	}
	
	public function showTemplate($templname, $vars = array(), $standalone = 0, $interface = APP_TYPE, $application = APPLICATION){
		return $this->parseTemplate($this->fetchTemplate($templname, $standalone, $interface, $application), $vars);
	}
	
	public function parseTemplate($file_data, $vars = array()){
		global $lang, $app;
		// Goddamnit. I really have to put this somewhere in a file. cbb_kernel? :D
		$uname = (isset($this->userController) ? $this->userController->getDisplayName() : ""); # Assign DISPLAY username..
		$unameR = (isset($this->userController) ? $this->userController->getUsername() : ""); # Assign LOGIN username..
		$loggedIn = ($this->uid > 0 ? true : false);
		$loggedInACP = (isset($_SESSION['cf_admin_username']) > 0 ? true : false);
		$unameACP = (($loggedInACP and isset($this->userController)) ? $this->userController->getDisplayName() : "");
		$uid = $this->uid;
		$file_data = preg_replace("/\{lang='([\w|\.]*)'}/e", "\$lang->getByKey('$1');", $file_data); # Language Variables - Priority
		$file_data = preg_replace("/\{langcopy}/e", "\$lang->langCopy();", $file_data); # Language Copyright - Priority
		$file_data = preg_replace("/\{appcopy}/e", "\$app->getApplicationCopyright()", $file_data); # Application-specific copyright
		$layoutcopy = ($this->layoutInfo['showStyleCopy'] ? "<b>{$lang->getByKey('core.layout')}:</b> {$this->layoutInfo['layoutCopyright']}" : "");
		$file_data = preg_replace("/\{layoutcopy}/e", "\$layoutcopy", $file_data); # Layout-specific copyright
		$file_data = preg_replace("/\{username}/e", "\$uname", $file_data); # User's current username
		$file_data = preg_replace("/\{usernamereal}/e", "\$unameR", $file_data); # User's current username (Real, not display)
		$file_data = preg_replace("/\{acpusername}/e", "\$unameACP", $file_data); # User's current username
		$file_data = preg_replace("/\{uid}/e", "\$uid", $file_data); # User's current UID
		$file_data = preg_replace("/\{rand:([0-9]*),([0-9]*)}/e", "rand($1, $2);", $file_data); # Random number {rand:min,max}
		$file_data = preg_replace("/\{date}/e", "date(\"F j, Y, g:i a\");", $file_data); # Curr Time
		preg_replace("/\{assign var='(.*)' value='(.*)'}/e", "' '.\$vars['$1'] = '$2';", $file_data); # eval'dcode :D
		$file_data = preg_replace("/\{assign var='(.*)' value='(.*)'}/", "", $file_data); # Remove assign tags as they were processed already
		foreach($vars as $k => $v){
			$file_data = preg_replace('/\{\$'.$k.'\}/si', $v, $file_data); # Parse tags
		}
		$file_data = preg_replace("/\{buildurl:app=(.*);module=(.*)}/", "?app=$1&module=$2", $file_data);
		$file_data = $this->outVars($file_data);
		$file_data = preg_replace("#\{if is_logged_in}([^{]*)\{/if}#si", ($loggedIn === true ? "$1" : ""), $file_data);
		$file_data = preg_replace("#\{if !is_logged_in}([^{]*)\{/if}#si", (!$loggedIn === true ? "$1" : ""), $file_data);
		$file_data = preg_replace("#\{if is_admin_logged_in}([^{]*)\{/if}#si", ($loggedInACP === true ? "$1" : ""), $file_data);
		return $file_data;
	}

	public function inlineError($message, $redirect = false){
		global $lang;
		$vars['message'] = $message;
		if($redirect){
			$vars['extra'] = "<br />".$this->generateRedirMeta($redirect)."<a href='{$redirect}'>".$lang->getByKey("view.redirecting")."</a>";
		}
		else{
			$vars['extra'] = "";
		}
		return $this->showTemplate("error", $vars, 1);
	}
	
	public function inlineWarning($message, $redirect = false){
		global $lang;
		$vars['message'] = $message;
		if($redirect){
			$vars['extra'] = "<br />".$this->generateRedirMeta($redirect)."<a href='{$redirect}'>".$lang->getByKey("view.redirecting")."</a>";
		}
		else{
			$vars['extra'] = "";
		}
		return $this->showTemplate("warning", $vars, 1);
	}
	
	public function inlineSuccess($message, $redirect = false){
		global $lang;
		$vars['message'] = $message;
		if($redirect){
			$vars['extra'] = "<br />".$this->generateRedirMeta($redirect)."<a href='{$redirect}'>".$lang->getByKey("view.redirecting")."</a>";
		}
		else{
			$vars['extra'] = "";
		}
		return $this->showTemplate("success", $vars, 1);
	}
	
	public function inlineInfo($message, $redirect = false){
		global $lang;
		$vars['message'] = $message;
		if($redirect){
			$vars['extra'] = "<br />".$this->generateRedirMeta($redirect)."<a href='{$redirect}'>".$lang->getByKey("view.redirecting")."</a>";
		}
		else{
			$vars['extra'] = "";
		}
		return $this->showTemplate("info", $vars, 1);
	}
	
	public function tablePadded($title, $message, $icon = 'table', $subtitle = false){
		$vars['content'] = $message;
		$vars['title'] = $title;
		$vars['icon'] = $icon;
		$vars['subtitle'] = ($subtitle ? $this->showTemplate("subtitle", array("content" => $subtitle), 1) : "");
		return $this->showTemplate("tablepadded", $vars, 1);
	}
	
	public function tableunpadded($title, $message, $icon = 'table', $subtitle = false){
		$vars['content'] = $message;
		$vars['title'] = $title;
		$vars['icon'] = $icon;
		$vars['subtitle'] = ($subtitle ? $this->showTemplate("subtitle", array("content" => $subtitle), 1) : "");
		return $this->showTemplate("tableunpadded", $vars, 1);
	}
	
	public function writeIn($content){
		$this->content .= $content;
	}
	
	/* Admin-specific functions... */
	
	public function writeSidebar($content){
		if(APP_TYPE == "backend") $this->layout->sidebar($content);
	}
	
	public function writeSidebarHead($content){
		if(APP_TYPE == "backend") $this->layout->sidebar($this->layout->sidebarHead($content), 1);
	}
	
	/** / End **/

	public function output(){
		$this->layout->content($this->content);
		echo $this->layout->getOutput();
	}
}
